package cn.lds.health.interceptor;

import cn.lds.health.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 登录拦截器，设定地址不登录无法访问
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取Session
        HttpSession session = request.getSession();
        //获取登录用户
        User user = (User) session.getAttribute("user");

        //如果登录用户为空
        if (Objects.isNull(user)){
            request.setAttribute("msg","请登录后访问");
            //转发页面到登录页面
            request.getRequestDispatcher("/user/login").forward(request,response);
        }

        return true;
    }
}
